const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 现金银行报表
router.post('/report/xjyhmx', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let formData = body.formData
    let tenantId = user.tenantId;
    let beginDate = formData.beginDate ? formData.beginDate: '2001-01-01';
    let endDate = formData.endDate?formData.endDate:tool.getDay();
    let buId = formData.buId?formData.buId:0;
    let accId = formData.accId?formData.accId:0;
    let salesId = formData.salesId?formData.salesId:0;
    let excel = body.excel
    let sqls = `
       exec list_xjyhbb @tenantId=${tenantId},@beginDate='${beginDate}',@endDate='${endDate}',@accId=${accId},@buId=${buId},@salesId=${salesId} ,@type='detail'
    `
    let list = await db.query(sqls, {type: QueryTypes.SELECT})
    let gp = tool.xe.groupBy(list, 'accId')
    let ret = []
    for(let i in gp) {
        let accs = gp[i];
        for (let j = 0; j < accs.length; j++) {
            let row = accs[j];
            // if(row.isInit === 1) row.accName = ''
            ret.push(row)
            if(j === accs.length - 1) {
                ret.push({
                    accId: row.accId,
                    accName: '',
                    transTypeName: '小计',
                    billNo:'',
                    billDate: '',
                    sr: tool.xe.sum(accs, 'sr'),
                    zc: tool.xe.sum(accs, 'zc'),
                    ye:0,
                    buName: '',
                    salesName: '',
                    remark: ''
                })
            }
        }
    }
    for (let i = 0; i < ret.length; i++) {
        let row = ret[i]
        if(row.isInit !== 1) row.ye = tool.xe.add(ret[i-1].ye, ret[i].ye)
    }
    if(excel) {
        return tool.doExcelOut(ctx, ret)
    }
    else {
        return ctx.suc('', {
            total: ret.length,
            list: ret
        })
    }


})

module.exports = router;
